package com.cooca.carborganizer.client;

import com.cooca.carborganizer.client.objects.User;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.*;

public class CarbOrganizerLogin implements EntryPoint, ClickListener {

	private DBConnectionAsync rpc;
	private TextBox usernameBox;
	private TextBox passwordBox;
	private Button OK;

	public CarbOrganizerLogin() {
		rpc = (DBConnectionAsync) GWT.create(DBConnection.class);
		ServiceDefTarget target = (ServiceDefTarget) rpc;
		String moduleRelativeURL = GWT.getModuleBaseURL() + "MySQLConnection";
		target.setServiceEntryPoint(moduleRelativeURL);
		System.out.println("OrganizerLogin initiiert...");	
		initGUI();
	}

	public void onModuleLoad() {
	//	RootPanel.get().add(this);
	}

	private void initGUI() {
		Grid g = new Grid(3, 2);
		usernameBox = new TextBox();
		passwordBox = new TextBox();
		OK = new Button("OK");
		g.setWidget(0, 0, new Label("Username:"));
		g.setWidget(0, 1, usernameBox);
		g.setWidget(1, 0, new Label("Password:"));
		g.setWidget(1, 1, passwordBox);
		g.setWidget(2, 1, OK);
		
		
		MyHandler handler = new MyHandler();
		OK.addClickHandler(handler);
		passwordBox.addKeyUpHandler(handler);
		RootPanel.get().add(g);
		
	}

	public void onClick(Widget sender) {
		if (sender.equals(OK)) {
			AsyncCallback<User> callback = new AuthenticationHandler<User>();
			rpc.authenticateUser(usernameBox.getText(), passwordBox.getText(),
					callback);
		}
	}
	
	
	class MyHandler implements ClickHandler, KeyUpHandler {
		public void onClick(ClickEvent event) {
			sendNameToServer();
		}

		public void onKeyUp(KeyUpEvent event) {
			if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
				sendNameToServer();
			}
		}

		private void sendNameToServer() {
			RootPanel.get().add(new HTML("RPC Aufruf gestartet (1.0)..."));
			AsyncCallback<User> callback = new AuthenticationHandler<User>();
			rpc.authenticateUser(usernameBox.getText(), passwordBox.getText(),callback);
		}
	}

	

	private class AuthenticationHandler<T> implements AsyncCallback<User> {

		public void onFailure(Throwable ex) {
			RootPanel.get().add(new HTML("RPC Aufruf Fehlerhaft. :-( "));
			RootPanel.get().add(new HTML(ex.getMessage()));
		}

		public void onSuccess(User result) {
			System.out.println("User gefunden : " + result);
			// do stuff on success with GUI, like load the next GUI element
		}

	}

}
